<?php

namespace services\base;

use common\helpers\ArrayHelper;
use common\models\common\TrueDeleteLog;
use common\models\patient\User;
use services\common\CommonService;
use Yii;
use common\components\Service;
use common\models\base\PatientDiseases;
use yii\data\Pagination;
use yii\db\ActiveRecord;

class PatientDiseasesService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return PatientDiseases|null
     */
    public function findById(int $id = 0): ?PatientDiseases
    {
        return PatientDiseases::find()->where(['id' => $id])->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @param null $orIds
     * @return array
     */
    public function findList(array $condition = [], $orIds = null): array
    {
        $query = PatientDiseases::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['pid']) && $query->andWhere(['pid' => $condition['pid']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        if (!is_null($orIds)) {// 编辑查找已绑定选项
            $query->orWhere([
                'id' => $orIds,
                'status' => [PatientDiseases::STATUS_INVALID, PatientDiseases::STATUS_ENABLE],
            ]);
        }
        isset($condition['indexBy']) && $query->indexBy($condition['indexBy']);

        return $query->asArray()->all();
    }


    /**
     * 获取病种父级列表
     *
     * @author wangxiang
     * @param int $pid
     * @return array
     */
    public static function getParentList(int $pid = 0)
    {
        $data = PatientDiseases::find()
            ->where(['status' => PatientDiseases::STATUS_ENABLE, 'pid' => $pid])
            ->select(['id value', 'diseases_name title'])
            ->asArray()
            ->all();

        return (array) $data;
    }

    /**
     * 获取病种列表数据
     *
     * @param array $params
     * @return array
     * @author wangxiang
     */
    public static function getList(array $params)
    {
        $query = PatientDiseases::find()
            ->where([
                'status' => [PatientDiseases::STATUS_ENABLE, PatientDiseases::STATUS_INVALID]
            ]);

        $total = $query->count();
        $data = $query
            ->orderBy(['status' => SORT_DESC, 'sort' => SORT_ASC])
            ->select(['id', 'pid', 'diseases_name', 'status', 'sort'])
            ->asArray()
            ->all();

        $data = ArrayHelper::tree($data);

        return ['list' => $data, 'total' => (int)$total, 'pageSize' => 0, 'page' => 1];
    }

    /**
     * 新增病种
     *
     * @param array $data
     * @return array
     * @throws \Exception
     * @author wangxiang
     */
    public static function createDiseases(array $params)
    {
        $pid = intval($params['pid'] ?? 0);
        $params['pid'] = $pid;
        $sort = $params['sort'] ?? '';

        //查询新建病种是否重名
        $exists = self::checkProfession(['and',
            ['pid' => $pid],
            ['diseases_name' => $params['diseases_name']],
            ['!=', 'status', PatientDiseases::STATUS_DELETE],
        ]);
        if ($exists) {
            return ['code' => 422, 'message' => '创建失败病种名重复',];
        }

        if ($sort === '') {
            $sortLastModel = PatientDiseases::find()
                ->where(['pid' => $pid])
                ->orderBy(['sort' => SORT_DESC])
                ->one();
            $sort = !empty($sortLastModel) ? $sortLastModel->sort : 0;
            $sort++;
        }

        $params['sort'] = intval($sort);

        $patientDiseases = new PatientDiseases();

        foreach ($params as $key => $value) {
            $patientDiseases->$key = $value;
        }

        if ($patientDiseases->save()) {
            // 删除缓存
            CommonService::baseRedis('patient_diseases', 2);

            return ['code' => 200, 'message' => 'success',];
        }

        return ['code' => 422, 'message' => '创建失败'];
    }


    /**
     * 编辑病种
     *
     * @param array $data
     * @param int $id
     * @return array
     * @throws \Exception
     * @author wangxiang
     */
    public static function updateDiseases(array $data, int $id)
    {
        $pid = intval($data['pid'] ?? 0);

        if ($data['status'] == PatientDiseases::STATUS_INVALID) {
            // 如果是禁用， 则需要判断其下级是否含有正常数据
            $flag = PatientDiseases::find()->where(['pid' => $id, 'status' => PatientDiseases::STATUS_ENABLE])->exists();
            if ($flag) {
                throw new \Exception('编辑失败, 该病种有子集数据！', 422);
            }
        }

        if ($pid == $id) {
            return ['code' => 422, 'message' => '不可以设为自己的下级'];
        }

        //查询是否重命名
        $model = PatientDiseases::find()->select('id')
            ->where(['diseases_name' => $data['diseases_name'], 'pid' => $pid])
            ->andWhere(['!=', 'status', PatientDiseases::STATUS_DELETE])
            ->one();
        if ($model && $model->id != $id) {
            return ['code' => 422, 'message' => '项目名重复',];
        }
        $model = PatientDiseases::findOne($id);
        $model->diseases_name = $data['diseases_name'];
        $model->pid = $pid;
        $model->sort = $data['sort'];
//        $model->relation_illness = $data['relation_illness'];
        $model->status = $data['status'];
        if (!$model->save()) {
            // 删除缓存
            CommonService::baseRedis('patient_diseases', 2);

            return ['code' => 422, 'message' => '更新病种失败',];
        }
        return ['code' => 200, 'message' => 'success',];


    }


    /**
     * 删除一条数据
     *
     * @param int $id
     * @return array
     * @throws \Exception
     * @author wangxiang
     */
    public static function deleteDiseases(int $id)
    {
        // 删除一条数据前需要判断其子集是否含有未删除的数据
        $flag = PatientDiseases::find()->where(['pid' => $id, 'status' => [PatientDiseases::STATUS_ENABLE, PatientDiseases::STATUS_INVALID]])->exists();
        if ($flag) {
            throw new \Exception('删除失败, 该病种有子集数据！', 422);
        }

        $model = PatientDiseases::findOne($id);
        $model->status = PatientDiseases::STATUS_DELETE;
        if (!$model->save()) {
            throw new \Exception('删除失败！', 500);
        }
        // 删除缓存
        CommonService::baseRedis('patient_diseases', 2);

        return ['id' => $model->id];
    }


    /**
     * 获取下拉数据
     *
     * @return array
     * @author wangxiang
     */
    public static function selectInfo()
    {
        $data = PatientIllnessState::find()->where([
            'status' => PatientIllnessState::STATUS_ENABLE,
            'pid' => 0
        ])->select(['id value', 'illness_name title'])->asArray()->all();

        return $data;
    }

    /**
     * 检查病情是否重复
     *
     * @param array $condition
     * @param int $id
     * @param int $type
     * @return bool
     */
    public static function checkProfession(array $condition, int $id = 0, int $type = 1)
    {
        $query = PatientDiseases::find()->where($condition);

        if ($id) {
            if ($type == 1) {
                $query->andWhere(['!=', 'id', $id]);
            } else {
                $query->andWhere(['id' => $id]);
            }
        }
        return $query->exists();
    }

    /**
     * 编辑病种状态
     *
     * @param int $id
     * @param int $status
     * @return array
     * @throws \Exception
     */
    public static function changeStatus(int $id, int $status)
    {
        if ($status == PatientDiseases::STATUS_INVALID) {
            // 如果是禁用， 则需要判断其下级是否含有正常数据
            $flag = PatientDiseases::find()->where(['pid' => $id, 'status' => PatientDiseases::STATUS_ENABLE])->exists();
            if ($flag) {
                throw new \Exception('编辑失败, 该病种有子集数据！', 422);
            }
        }

        if ($status == PatientDiseases::STATUS_DELETE) {
            // 如果是删除， 则需要判断其下级是否含有未禁用和正常数据
            $flag = PatientDiseases::find()->where(['pid' => $id, 'status' => [PatientDiseases::STATUS_ENABLE, PatientDiseases::STATUS_INVALID]])->exists();
            if ($flag) {
                throw new \Exception('编辑失败, 该病种有子集数据！', 422);
            }
        }

        $model = PatientDiseases::findOne($id);
        $model->status = $status;
        if (!$model->save()) {
            throw new \Exception(json_encode($model->errors), 500);
        }

        // 删除缓存
        CommonService::baseRedis('patient_diseases', 2);

        return ['status' => $status, 'id' => $id];
    }


    public function trueDelete(int $id)
    {
        $diseasesArray = PatientDiseases::find()
            ->select('id, diseases_name, pid')
            ->where(['id' => $id])
            ->asArray()
            ->all();

        if (!$diseasesArray) {
            return ['code' => 422, 'message' => '该效果类型不存在'];
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            $member = Yii::$app->user->identity->member;

            // 如果是
            if ($diseasesArray[0]['pid'] == 0) {

                $diseasesIds[] = $diseasesArray[0]['id'];

                // 需要筛选全部子集批量删除
                $childDiseases = PatientDiseases::find()
                    ->select('id, diseases_name, pid')
                    ->andWhere(['>', 'pid', 0])
                    ->asArray()
                    ->all();

                $childDiseasesArray = ArrayHelper::getChilds($childDiseases,$id);

                foreach ($childDiseasesArray as $value) {
                    $diseasesArray[] = $value;
                    $diseasesChildIds[] = $value['id'];
                }

            } else {
                $diseasesChildIds = $diseasesArray[0]['id'];
            }


            foreach ($diseasesArray as $data) {
                $insertData[] = [
                    'project_id' => 0,
                    'delete_id' => $data['id'],
                    'delete_name' => $data['diseases_name'],
                    'delete_table' => PatientDiseases::tableName(),
                    'effect_table' => '【' . User::tableName() . '（patient_diseases_id,patient_diseases_child_id）】',
                    'operator_id' => $member->id,
                    'operator_name' => $member->realname,
                    'created_at' => time(),
                    'updated_at' => time()
                ];
            }

            $ids = array_column($diseasesArray,'id');
            // 删除病种
            $data = PatientDiseases::deleteAll(['id' => $ids]);

            // 清空 一级病种
            !empty($diseasesIds) && User::updateAll(['updated_at' => time(), 'patient_diseases_id' => 0],['patient_diseases_id' => $diseasesIds]);
            //  清空 二级病种
            !empty($diseasesChildIds) && User::updateAll(['updated_at' => time(), 'patient_diseases_child_id' => 0],['patient_diseases_child_id' => $diseasesChildIds]);

            // 记录修改记录
            Yii::$app->db->createCommand()->batchInsert(TrueDeleteLog::tableName(),[
                'project_id', 'delete_id', 'delete_name', 'delete_table', 'effect_table', 'operator_id', 'operator_name', 'created_at', 'updated_at'
            ],$insertData);

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }

        if (!$data) {
            return ['code' => 422, 'message' => '删除失败'];
        }

        // 删除缓存
        CommonService::baseRedis('patient_diseases', 2);

        return ['code' => 200, 'message' => '删除成功'];
    }

}
